from datetime import datetime

from sqlalchemy import Integer, Column, String, Enum, DateTime, ForeignKey, Float, Text, PrimaryKeyConstraint, text, \
    Index, func,ARRAY
from sqlalchemy.orm import relationship

from src.extension import db
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import JSONB

class Exercise(db.Model):
    """习题表模型"""
    __tablename__ = 'exercises'
    __table_args__ = (
        PrimaryKeyConstraint('exercise_id', name='exercises_pkey'),
        Index('branch_pk', 'branch'),
    )
    exercise_id = Column(Integer, nullable=False, autoincrement=True)
    subject = Column(String(50), nullable=False)
    user_id = Column(Integer, ForeignKey('users.user_id'), nullable=False)
    category_id = Column(Integer, ForeignKey('categorys.id'), nullable=False)
    question_text = Column(Text, nullable=False)
    compile=Column(Integer, nullable=False)
    similarit_category =  Column(ARRAY(JSONB), server_default=text("'{}'::jsonb[]"))
    answer_result=Column(String, nullable=False)
    score=Column(Integer, nullable=False)
    branch_id=Column(String, nullable=False)
    exercises_main_id =  Column(Integer, ForeignKey('exercise_mans.id'))

    branch = Column(String, nullable=False)
    answer_text = Column(Text, nullable=False)
    created_at = Column(DateTime, nullable=False, server_default=text('CURRENT_TIMESTAMP(0)'))
    updated_at = Column(DateTime, nullable=False, server_default=text('CURRENT_TIMESTAMP(0)'),
                        server_onupdate=text('CURRENT_TIMESTAMP(0)'))

    category = relationship("Category")
    @property
    def getTotalCount(self):

        return (db.session.query(func.coalesce(func.count(Exercise.exercise_id), 0)).
                filter(Exercise.branch_id==self.branch_id,Exercise.user_id==self.user_id)).scalar()
    @property
    def getCount(self):
        return (db.session.query(func.coalesce(func.count(Exercise.exercise_id), 0)).
                filter(Exercise.branch_id==self.branch_id,Exercise.user_id==self.user_id,Exercise.compile==1)).scalar()
    @property
    def getCatgory(self):
        from src.model import Category

        return db.session.query(Category).filter(Category.id==self.category_id).one_or_none()
    @property
    def student_answers(self):
        from src.model import StudentAnswer
        print(self.exercise_id)
        return db.session.query(StudentAnswer).filter(StudentAnswer.exercise_id==self.exercise_id).first()
